package com.juyu.reader.pc.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient.Builder;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.stereotype.Service;

import com.juyu.reader.pc.common.Configure;
import com.juyu.reader.pc.model.Book;
import com.juyu.reader.pc.util.StringUtil;

@Service
public class SolrService {
	private static HttpSolrClient client;

	/**
	 * 获取solr客户端
	 * 
	 * @return
	 */
	private HttpSolrClient getHttpSolrClient() {

		if (client == null) {
			client = new Builder().withBaseSolrUrl(Configure.solrUrl).build();
			return client;
		}
		return client;
	}

	/**
	 * 创建书籍索引
	 * 
	 * @param book
	 */
	public void createIndex(List<Book> bookList) throws Exception {
		// 创建索引
		List<SolrInputDocument> docList = new ArrayList<SolrInputDocument>();
		for (Book b : bookList) {
			SolrInputDocument doc = new SolrInputDocument();
			doc.addField("id", b.getBookId());
			doc.addField("book_name", b.getBookName());
			doc.addField("book_author", b.getBookAuthor());
			doc.addField("book_desc", b.getBookDesc());
			
			doc.addField("book_words", b.getBookWords());
			doc.addField("book_image_type", b.getBookImageType());
			doc.addField("book_image", b.getBookImage());
			doc.addField("book_category", b.getBookCategoryName());
			doc.addField("book_flag", b.getBookFlag());
			doc.addField("book_reward", b.getBookReward());
			doc.addField("book_forward", b.getBookForward());
			docList.add(doc);
		}
		this.getHttpSolrClient().add(docList);
		this.getHttpSolrClient().commit();
	}

	public void deleteIndexById() {

	}

	/**
	 * 查询书籍
	 * 
	 * @param keyStr关键字
	 * @param page
	 *            分页
	 * @param limit
	 *            记录数
	 *
	 * @return
	 */
	public List<Book> searchBook(String keyStr, int page, int limit) throws Exception {
		List<Book> bookList = new ArrayList<Book>();
		SolrQuery query = new SolrQuery();// 查询
		// q 查询字符串，如果查询所有*:*
		if (StringUtil.isNullOrEmpty(keyStr)) {
			keyStr = "*";
		}
		query.set("q", "book_author:" + keyStr + " and book_name:" + keyStr);
		// fq 过滤条件，过滤是基于查询结果中的过滤
		// query.set("fq", "book_desc:白裙");
		// df 默认搜索的域
		query.set("df", "book_name");
		// 开启高亮
		query.setHighlight(true);
		// 高亮域
		query.addHighlightField("book_author,book_name,book_desc");
		// 前缀
		query.setHighlightSimplePre("<font color='#ff0000'>");
		// 后缀
		query.setHighlightSimplePost("</font>");
		int start = limit * (page - 1);
		if (start <= 0) {
			start = 0;
		}
		query.setStart(start);
		query.setRows(limit);

		// 执行搜索
		QueryResponse queryResponse = this.getHttpSolrClient().query(query);
		// 搜索结果
		SolrDocumentList results = queryResponse.getResults();
		// 查询出来的数量
		// long numFound = results.getNumFound();
		// System.out.println("总查询出:" + numFound + "条记录");
		// 获取高亮信息
		Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
		for (SolrDocument sd : results) {
			Book book = new Book();
			book.setSearchBookCount((int)results.getNumFound());
			book.setBookId(Integer.valueOf(sd.getFieldValue("id").toString()));
			// sd.getFieldValue("book_name")含有中括号[]，所以转成数组后获取第一个
			List<String> bookNameList = (List<String>) sd.getFieldValue("book_name");
			if (bookNameList != null && bookNameList.size() > 0) {
				book.setBookName(bookNameList.get(0));
			}
			List<String> bookAuthorList = (List<String>) sd.getFieldValue("book_author");
			if (bookAuthorList != null && bookAuthorList.size() > 0) {
				book.setBookAuthor(bookAuthorList.get(0));
			}
			List<String> bookDescList = (List<String>) sd.getFieldValue("book_desc");
			if (bookDescList != null && bookDescList.size() > 0) {
				book.setBookDesc(bookDescList.get(0));
			}
			List<Long> bookWordsList = (List<Long>) sd.getFieldValue("book_words");
			if (bookWordsList != null && bookWordsList.size() > 0) {
				book.setBookWords(bookWordsList.get(0));
			}
			List<Long> bookImageTypeList = (List<Long>) sd.getFieldValue("book_image_type");
			if (bookImageTypeList != null && bookImageTypeList.size() > 0) {
				book.setBookImageType(bookImageTypeList.get(0).intValue());
			}
			List<String> bookImageList = (List<String>) sd.getFieldValue("book_image");
			if (bookImageList != null && bookImageList.size() > 0) {
				book.setBookImage(bookImageList.get(0));
			}
			List<String> bookCategoryList = (List<String>) sd.getFieldValue("book_category");
			if (bookCategoryList != null && bookCategoryList.size() > 0) {
				book.setBookCategoryName(bookCategoryList.get(0));
			}
			List<Long> bookFlagList = (List<Long>) sd.getFieldValue("book_flag");
			if (bookFlagList != null && bookFlagList.size() > 0) {
				book.setBookFlag(bookFlagList.get(0).intValue());
			}
			List<Long> bookRewardList = (List<Long>) sd.getFieldValue("book_reward");
			if (bookRewardList != null && bookRewardList.size() > 0) {
				book.setBookReward(bookRewardList.get(0).intValue());
			}
			List<Long> bookForwardList = (List<Long>) sd.getFieldValue("book_forward");
			if (bookForwardList != null && bookForwardList.size() > 0) {
				book.setBookForward(bookForwardList.get(0).intValue());
			}

			// 输出高亮
			Map<String, List<String>> map = highlighting.get(sd.get("id"));

			List<String> list1 = map.get("book_name");
			if (list1 != null && list1.size() > 0) {
				// System.out.println(list1.get(0));
				book.setBookNameHL(list1.get(0));
			}
			List<String> list2 = map.get("book_author");
			if (list2 != null && list2.size() > 0) {
				// System.out.println(list2.get(0));
				book.setBookAuthorHL(list2.get(0));
			}
			List<String> list3 = map.get("book_desc");
			if (list3 != null && list3.size() > 0) {
				// System.out.println(list3.get(0));
				book.setBookDescHL(list3.get(0));
			}
			bookList.add(book);

		}
		return bookList;
	}
}
